package leetcode.code0059;

public class Solution extends Solution59 {

	int[][] ans;

	@Override
	public int[][] generateMatrix(int n) {
		ans = new int[n][n];
		f0(0, 0, n - 1, n - 1, 1);// 首行,首列,末行,末列,写入的第一个数字
		return ans;
	}

	private void f0(int sr, int sc, int er, int ec, int num) {
		if (sc > ec)
			return;
		for (int i = sc; i <= ec; i++) { // f0,在sr(首行)上, 从第一列到最后一列
			ans[sr][i] = num++;
		}
		f1(sr + 1, sc, er, ec, num);
	}

	private void f1(int sr, int sc, int er, int ec, int num) {
		if (sr > er)
			return;
		for (int i = sr; i <= er; i++) { // f1,在ec(末列)上, 从第一行到最后一行
			ans[i][ec] = num++;
		}
		f2(sr, sc, er, ec - 1, num);
	}

	private void f2(int sr, int sc, int er, int ec, int num) {
		if (sc > ec)
			return;
		for (int i = ec; i >= sc; i--) { // f2,在er(末行)上, 从最后一列到第一列
			ans[er][i] = num++;
		}
		f3(sr, sc, er - 1, ec, num);
	}

	private void f3(int sr, int sc, int er, int ec, int num) {
		if (sr > er)
			return;
		for (int i = er; i >= sr; i--) { // f3,在sc(首列)上, 从最后一行到第一行
			ans[i][sc] = num++;
		}
		f0(sr, sc + 1, er, ec, num);
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
	}

}
